#include "FreeRTOS.h"
#include "task.h"
#include "stm32f4xx_hal.h"
#include <stdio.h>
#include <string.h>
#include "./stm32f401_pico_led.h"
#include "./stm32f401_pico_key.h"
#include "./stm32f401_pico_uart.h"
#include "./stm32f401_pico_i2c.h"

// 函数声明
void Error_Handler(void);
void SystemClock_Config(void);

// 主函数：初始化并创建任务
void pico_main(void)
{
    HAL_Init();
    SystemClock_Config();
    MX_USART1_UART_Init();

    // 创建LED任务
    xTaskCreate(
        (TaskFunction_t)Led_Task,
        (const char *)"Led_Task",
        (uint16_t)configMINIMAL_STACK_SIZE,
        (void*)NULL,
        (UBaseType_t)2,  
        (TaskHandle_t*)&led_task_handle
    );

    // 创建KEY任务
    xTaskCreate(
        (TaskFunction_t)Key_Task,
        (const char *)"Key_Task",
        (uint16_t)configMINIMAL_STACK_SIZE,
        (void*)NULL,
        (UBaseType_t)3,  
        (TaskHandle_t*)&key_task_handle
    );

    //创建I2C任务
    // xTaskCreate(
    //     (TaskFunction_t)I2C_Task,
    //     (const char *)"I2C_Task",
    //     (uint16_t)configMINIMAL_STACK_SIZE * 2,
    //     (void*)NULL,
    //     (UBaseType_t)1,
    //     (TaskHandle_t*)&i2c_task_handle
    // );

    //创建UART任务
    // xTaskCreate(
    //     (TaskFunction_t)UART_Task,
    //     (const char *)"UART_Task",
    //     (uint16_t)configMINIMAL_STACK_SIZE,
    //     (void*)NULL,
    //     (UBaseType_t)5,
    //     (TaskHandle_t*)&uart_task_handle
    // );

    vTaskStartScheduler();  // 启动任务调度器
}

// 系统时钟配置
void SystemClock_Config(void)
{
    RCC_OscInitTypeDef RCC_OscInitStruct = {0};
    RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

    RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
    RCC_OscInitStruct.HSIState = RCC_HSI_ON;
    RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
    RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
    if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
    {
        Error_Handler();
    }

    RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                                 |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
    RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HSI;
    RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
    RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
    RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
    if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0) != HAL_OK)
    {
        Error_Handler();
    }
}
